
import BaseService from "./BaseService";
export default class WXSocketService extends BaseService {

    protected socket: any;


    destroy() {
        if (this.socket != null) {
            this.socket.close();
            this.socket = null;
        }
    }
    //手动重联
    reConnect() {
        this.connect();
    }

    onData(event) {
        super.onData(event.data);
    }

    connect() {
        this.destroy();
        try {
            this.socket = window['wx']['connectSocket']({
                url: this.url,
                header: {
                    "content-type": "application/octet-stream",
                    "accept": "application/octet-stream",
                },
                method: "POST",
                protocols: [],
                success: function (res) {
                    console.log("WS连接成功, ", res);
                },
                fail: function (res) {
                    console.log("WS连接失败, ", res);
                },
                complete: function (res) {
                    console.log("complete ", res);
                },
            });
            this.socket.onOpen(this.onOpen.bind(this));
            this.socket.onMessage(this.onData.bind(this));
            this.socket.onError(this.onError.bind(this));
            this.socket.onClose(this.onClose.bind(this));
        } catch (error) {
            console.log("WebService connect error " + error);
        }
    }

    sendData(message: net.SendMessage) {
        if (this.isReady()) {
            let msg = message.data
            this.socket.send({
                data: msg,
                success: function (res) {
                },
                fail: function (res) {
                },
                complete: function (res) { },
            });
        } else {
            console.warn(" 请先连接服务器 ", this.url);
        }
    }


}
